﻿using System;
using System.Web.Security;
using axCommerce.Data;
using axCommerce.Helper;

namespace axCommerce.Membership
{
	public class UserRepository
	{
		public MembershipUser CreateUser(string username, string password, string email, bool isActivated)
		{
			string sPasswordSalt = CryptoHelper.CreateSalt();

			Account account = new Account
								{
									Email = email,
									Password = CryptoHelper.CreatePasswordHash(password, sPasswordSalt),
									PasswordSalt = sPasswordSalt,
									IsActivated = isActivated
								};
			account.Save();

			return GetUser(username);
		}

		public bool ActivateUser(string email, string key)
		{
			Account account = Account.SearchByEmail(email);
			if (account != null)
			{
				if (account.NewEmailKey == key)
				{
					account.IsActivated = true;
					account.NewEmailKey = null;

					account.UpdateInstance();
					return true;
				}
				return false;
			}
			return false;
		}

		public MembershipUser GetUser(string email)
		{
			Account account = Account.SearchByEmail(email);

			if (account == null || account.AccountId == null || account.IsActivated == null || account.IsLockedOut == null || 
				account.CreatedDate == null || account.LastLoginDate == null || account.LastLockedOutDate == null)
				return null;
			
			int providerUserKey = account.AccountId.Value;
			string passwordQuestion = String.Empty;
			string comment = account.Comments;
			bool isApproved = account.IsActivated.Value;
			bool isLockedOut = account.IsLockedOut.Value;
			DateTime creationDate = account.CreatedDate.Value;
			DateTime lastLoginDate = account.LastLoginDate.Value;
			DateTime lastActivityDate = DateTime.Now;
			DateTime lastPasswordChangedDate = DateTime.Now;
			DateTime lastLockedOutDate = account.LastLockedOutDate.Value;

			return new MembershipUser("AxMembershipProvider",
			                          email,
			                          providerUserKey,
			                          email,
			                          passwordQuestion,
			                          comment,
			                          isApproved,
			                          isLockedOut,
			                          creationDate,
			                          lastLoginDate,
			                          lastActivityDate,
			                          lastPasswordChangedDate,
			                          lastLockedOutDate);
		}
	}
}